<?php

namespace App\Kuafu\Dashboard\Controller\B;

use App\Http\Controllers\Controller;
use App\Kuafu\Brand\Service\BrandService;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Dashboard\Service\DashboardService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Sys\Enum\SysMenusCodeEnum;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserRoleService;
use Illuminate\Http\Request;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;

class DashboardController extends BaseController
{

    /**
     * 获取面板的配置
     * @param Request $request
     */
    public function index(Request $request)
    {
        $userId   = AuthService::getUserId();
//        $userId   = 1945;
        $platform = CodeEnum::PLATFORM_B_BRAND;

        // 获取当前用户的角色 ID
        $roleList = UserRoleService::getWebUserRoleList($userId, $this->brandId, $this->shopId);

        if (empty($roleList)) {
            return $this->fail(BaseCodeEnum::ERR_NO_ACCESS);
        }

        $menusList = DashboardService::getMenusV2($roleList, $platform);

        // 判断用户是否绑定了飞书账号
        $userInfo = AuthService::getAuthUser();
        if (empty($userInfo->feishuUserId)) {
            $menusList = array_column($menusList, null, 'id');
            if (!empty($menusList[SysMenusCodeEnum::MENUS_QIAN_YUE_ID])) {
                unset($menusList[SysMenusCodeEnum::MENUS_QIAN_YUE_ID]); // TODO 先写死 删除 "签约开店" 这个模块,后期做通用配置删除
            }
            $menusList = array_values($menusList);
        }

        $return = [
            'menusList' => $menusList
        ];
        // 获取当前用户展示的菜单
        return $this->success($return);
    }


    /**
     * 展示店铺列表
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Kuafu\User\Exceptions\UserException
     */
    public function shopList()
    {
        $userId = AuthService::getUserId();

        // 获取当前角色的品牌列表
        $brandList = BrandService::getBrandListByUserId($userId);
        $brandList = array_column($brandList, null, 'id');

        foreach ($brandList as &$brandValue) {
            $brandValue['shopList'] = [];
        }
        unset($brandValue);

        // 获取当前用户有的店铺列表
        $shopList = ShopService::getShopListByUserId($userId);

        foreach ($shopList as $shop) {
            if (!empty($brandList[$shop['brandId']])) {
                $brandList[$shop['brandId']]['shopList'][] = $shop;
            }
        }
        $brandList = array_values($brandList);

        return $this->success($brandList);
    }
}
